package org.wannatrak.android.service;

import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import org.wannatrak.android.entity.Setting;

/**
 * @Author: Maksim Tulupov maxtulupov@gmail.com
 * @Date: $Date: 2011-06-20 05:08:37 +0000 (Mon, 20 Jun 2011) $
 * @Time: 13:49:46
 * @Version: $Revision: 13 $
 * @Id: $Id: SettingService.java 13 2011-06-20 05:08:37Z maxtulupov@gmail.com $
 */
public class SettingService {

    private Context context;

    public SettingService(Context context) {
        this.context = context;
    }

    public String loadSetting(String name) {
        Cursor c = null;
        try {
            c = context.getContentResolver().query(Setting.CONTENT_URI, null, Setting.NAME + " = ?", new String[]{name}, null);
            if (c.moveToFirst() && !c.isNull(c.getColumnIndex(Setting.VALUE))) {
                return c.getString(c.getColumnIndex(Setting.VALUE));
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return null;
    }

    public void saveSetting(String name, String value) {
        String val = loadSetting(name);
        ContentValues cv = new ContentValues();
        cv.put(Setting.VALUE, value);
        if (val == null) {
            cv.put(Setting.NAME, name);
            context.getContentResolver().insert(Setting.CONTENT_URI, cv);
        } else {
            context.getContentResolver().update(Setting.CONTENT_URI, cv, Setting.NAME + " = ?", new String[]{name});
        }
    }

    public void removeSetting(String name) {
        context.getContentResolver().delete(Setting.CONTENT_URI, Setting.NAME + " = ?", new String[] {name});
    }
}
